﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.IO;

namespace Cms.Web
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath("log4net.cfg.xml")));
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpRequest request = HttpContext.Current.Request;
            string rawurl = request.RawUrl;

            string exreg = ".js|.css|.jpg|.gif|.png|.jpeg|.htc|.tiff|.ico|.icon";
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(exreg, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (!regex.IsMatch(rawurl))
            {
                Uri uri = request.UrlReferrer;
                Model.PageLog modelLog = new Cms.Model.PageLog();
                modelLog.Url = rawurl;
                if (uri != null)
                    modelLog.Refurl = uri.ToString();
                modelLog.VisitDate = DateTime.Now;
                modelLog.Ip = request.UserHostAddress;
                modelLog.Browser = request.Browser.Browser + ";" + request.Browser.Version;
                BLL.PageLog blllog = new Cms.BLL.PageLog();
                blllog.AddLog(modelLog);
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpRequest request = HttpContext.Current.Request; string rawurl = request.RawUrl;
            string rawpath = request.Path.ToLower();
            if (rawpath.IndexOf("/cmssystem/") > -1
                && rawpath.IndexOf("login.aspx") < 0
                && rawpath.IndexOf("default.aspx") < 0
                && (HttpContext.Current.User == null || !HttpContext.Current.User.Identity.IsAuthenticated))
            {
                HttpContext.Current.Response.Redirect("~/CmsSystem/Login.aspx?ReturnUrl=" + HttpContext.Current.Server.UrlEncode(rawurl));
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {
          
          //  EntLib.LogHelper.GetInstance().Error(
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}